﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Web.Ajax.Data
{
	public class HashtableExtensions 
	{
		public static string TranslateName(string name, DataAttribute.ColumnName[] cl)
		{
			if (cl == null)
				return name;
			var cx = cl.FirstOrDefault(c => c.Name == name);
			if (cx != null)
				return cx.SqlName;
			return name;
		}

		public static System.Collections.Hashtable Convert(object o, DataAttribute.ColumnName[] explicitFields=null)
		{
			if (o == null)
				return null;
			if (o is System.Collections.Hashtable)
				return (System.Collections.Hashtable) o;

			var t=o.GetType();
			var fields = t.GetFields();

			var props = t.GetProperties();


			if (explicitFields != null)
			{
				var explicitNames = explicitFields.Select(f => f.Name).ToArray();
				fields = (from f in fields where explicitNames.Contains(f.Name) select f).ToArray();
				props = (from p in props where explicitNames.Contains(p.Name) select p).ToArray();
			}

			var h = new System.Collections.Hashtable();

			foreach (var fi in fields)
			{
				var v = fi.GetValue(o);
				var n = TranslateName(fi.Name, explicitFields);
				if (fi.FieldType.IsClass && fi.FieldType!=typeof(string))
					v = Convert(v);
				h[n] = v;
			}
			foreach (var p in props)
			{
				var v = p.GetValue(o, null);
				var n = TranslateName(p.Name, explicitFields);
				if (p.PropertyType.IsClass && p.PropertyType != typeof(string))
					v = Convert(v);
				h[n] = v;
			}
			return h;
		}
	}
}
